package com.lzc.tlmail.tlmailmenber.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lzc.common.utils.HttpUtils;
import com.lzc.common.vo.OauthUser;
import com.lzc.tlmail.tlmailmenber.entity.MemberLevelEntity;
import com.lzc.tlmail.tlmailmenber.exception.PhoneExitsException;
import com.lzc.tlmail.tlmailmenber.exception.UserNameExitsException;
import com.lzc.tlmail.tlmailmenber.service.MemberLevelService;
import com.lzc.tlmail.tlmailmenber.vo.LoginVo;
import com.lzc.tlmail.tlmailmenber.vo.RegistVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzc.common.utils.PageUtils;
import com.lzc.common.utils.Query;

import com.lzc.tlmail.tlmailmenber.dao.MemberDao;
import com.lzc.tlmail.tlmailmenber.entity.MemberEntity;
import com.lzc.tlmail.tlmailmenber.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;

    @Autowired
    private MemberService memberService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 会员注册方法
     * @param registVo
     */
    @Override
    public void regist(RegistVo registVo) {
        MemberEntity memberEntity = new MemberEntity();
        //得到默认等级赋值
        MemberLevelEntity memberLevelEntity = memberLevelService.getOne(new LambdaQueryWrapper<MemberLevelEntity>()
                .eq(MemberLevelEntity::getDefaultStatus, 1));
        memberEntity.setLevelId(memberLevelEntity.getId());
        memberService.selectUserByUserName(registVo.getUserName());
        memberService.selectUserByPhone(registVo.getPhone());
        memberEntity.setUsername(registVo.getUserName());
        memberEntity.setNickname(registVo.getUserName());
        memberEntity.setMobile(registVo.getPhone());
        //使用md5加盐值加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(registVo.getPassword());
        memberEntity.setPassword(encode);

        this.getBaseMapper().insert(memberEntity);
    }

    /**
     * 查询用户名是否存在
     * @param userName
     */
    @Override
    public void selectUserByUserName(String userName) throws UserNameExitsException{
        Integer integer = this.getBaseMapper().selectCount(new LambdaQueryWrapper<MemberEntity>()
                .eq(MemberEntity::getUsername, userName));
        if(integer>0){
            throw new UserNameExitsException();
        }
    }

    /**
     * 查询手机号是否存在
     * @param phone
     */
    @Override
    public void selectUserByPhone(String phone) throws PhoneExitsException{
        Integer integer = this.getBaseMapper().selectCount(new LambdaQueryWrapper<MemberEntity>()
                .eq(MemberEntity::getMobile,phone));
        if(integer>0){
            throw new PhoneExitsException();
        }
    }

    /**
     * 登录方法
     * @param loginVo
     * @return
     */
    @Override
    public MemberEntity login(LoginVo loginVo) {
        MemberEntity memberEntity = this.getBaseMapper().selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, loginVo.getUserName())
                .or().eq(MemberEntity::getMobile, loginVo.getUserName()));
        if(memberEntity==null){
            return null;
        }else {
            String password = loginVo.getPassword();
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, memberEntity.getPassword());
            if(matches){
                return memberEntity;
            }else {
                return null;
            }

        }
    }

    /**
     * 社交登录
     * @param oauthUser
     * @return
     */
    @Override
    public MemberEntity login(OauthUser oauthUser) throws Exception {
        String uid = oauthUser.getUid();
        MemberDao memberDao = this.getBaseMapper();
        MemberEntity memberEntity = memberDao.selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUid, uid));
        if(memberEntity!=null){
            memberEntity.setAccessToken(oauthUser.getAccess_token());
            memberEntity.setUid(uid);
            memberEntity.setRemindIn(oauthUser.getRemind_in());
            memberDao.updateById(memberEntity);
            return memberEntity;
        }else {
            MemberEntity regist = new MemberEntity();
            try {
                Map<String, String> query=new HashMap<String, String>();
                query.put("uid",oauthUser.getUid());
                HttpResponse response = HttpUtils.doGet("http://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if(response.getStatusLine().getStatusCode()==200){
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender)?1:0);
                    //...等等
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            regist.setUid(uid);
            regist.setAccessToken(oauthUser.getAccess_token());
            regist.setRemindIn(oauthUser.getRemind_in());
            memberDao.insert(regist);
            return regist;
        }

    }

}